package com.yuzhitong.shapi.base;


import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import androidx.lifecycle.Lifecycle;


import a.a.a.MyApplication;
import com.yuzhitong.shapi.util.LoggerUtil;
import com.yuzhitong.shapi.util.StringUtil;
import com.yuzhitong.shapi.widget.LoadingDialog;

import autodispose2.AutoDispose;
import autodispose2.AutoDisposeConverter;
import autodispose2.androidx.lifecycle.AndroidLifecycleScopeProvider;

/**
 * MVP模式Activity基类
 * @param <T> 使用的Presenter
 */
public abstract class BaseMvpActivity<T extends BasePresenter> extends BaseLayoutActivity implements BaseView {
    protected T presenter;
    private LoadingDialog loadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isProxy();
        initPresenter();

    }

    protected abstract void initPresenter();

    @Override
    protected void onDestroy() {
        if (presenter != null) {
            presenter.detachView();
        }
        super.onDestroy();
    }

    /**
     * 绑定生命周期 防止MVP内存泄漏
     *
     * @param <T>
     * @return
     */
    @Override
    public <T> AutoDisposeConverter<T> bindAutoDispose() {
        return AutoDispose.autoDisposable(AndroidLifecycleScopeProvider
                .from(this, Lifecycle.Event.ON_DESTROY));
    }

    @Override
    public void onFail(int status, String msg) {
        hideLoading();
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }


    @Override
    public void showLoading() {
        if (loadingDialog == null) {
            loadingDialog = new LoadingDialog(this);
        }
        loadingDialog.show();
    }

    @Override
    public void hideLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
    }

    @Override
    public void onError(String errMessage) {
        hideLoading();
        Toast.makeText(this, "网络错误，请重试", Toast.LENGTH_SHORT).show();
        Log.e(Contents.LOG_TAG, "onError: " + errMessage);
    }


    public boolean isProxy() {
        String proxyAddress = System.getProperty("http.proxyHost");
        LoggerUtil.e("daili::: " + proxyAddress);
        ConnectivityManager connectivityManager=
                (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_VPN);
        boolean isVpnConn = networkInfo != null && networkInfo.isConnected();
        LoggerUtil.e("开启代理: " + isVpnConn);
        MyApplication.setIsProxy(isVpnConn && StringUtil.isEmpty(proxyAddress));
        return isVpnConn && StringUtil.isEmpty(proxyAddress);
    }

}
